package cn.q3c.stock.task;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;

/**
 * 文件下载线程
 * 
 * @author Yoyo
 * 
 */
public class DownloadFiles implements Runnable {

	private static Logger logger = Logger.getLogger(DownloadFiles.class);

	private URL url;
	private File file;

	public DownloadFiles(URL url, File file) {
		this.url = url;
		this.file = file;
	}

	public void run() {

		try {
			
			//临时文件，然后改名
			File tempFile = new File( file + ".tmp" );
			FileUtils.copyURLToFile(url, tempFile,
					(int) DateUtils.MILLIS_PER_MINUTE*5,
					(int) DateUtils.MILLIS_PER_MINUTE*5);
			FileUtils.moveFile(tempFile, file);
			
			//<1k，清空
			if( FileUtils.sizeOf(file) < FileUtils.ONE_KB )
			{
				FileUtils.write(file, "");
			}
			
			logger.debug("download " + file + ";size=" + FileUtils.sizeOf(file)/FileUtils.ONE_KB + "kb");
			
		} catch (Exception e) {
			
			logger.error("文件下载失败：url=" + url + ";file=" + file + " " + e.getMessage());
			
		}
	}
}
